package com.lzp.java.concurrent.flowcontrol.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author lzp
 * @Description: 演示Semaphore的使用
 * @date 2021/3/6
 */
public class SemaphoreDemo {
    private static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Task task = new Task();
        for (int i = 0; i < 10; i++) {
            pool.submit(task);
        }
        pool.shutdown();
    }

    static class Task implements Runnable {
        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + "获取到许可证");
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "释放许可证");
                semaphore.release();
            }
        }
    }
}
